﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using FluorineFx;
using FluorineFx.AMF3;
using FluorineFx.Data;
using FluorineFx.Context;
using MySql.Data.MySqlClient;
using Could.Service.Utilitis;
using System.Xml;
using AppModule.InterProcessComm;
using AppModule.NamedPipes;
using CatSentenceAnalyzer;

namespace Could.Service
{
    [FluorineFx.RemotingService("Web Could Translation ServiceLibrary")]
    public class TransLib
    {
        private Hashtable m_IndexTable = new Hashtable(); 
        private const string NAMEPIPE = "NAMWPIPE_NTSERVICE";
        public TransData FindSentenceTest( string otxt, string ttxt, int userid){
            TransData td = new TransData();
            td.OSentence = otxt;
            td.TSentence = ttxt;
            td.TmsTitle = "匹配结果: 获得约100条结果, 用时(0.05秒)";
            td.TmsResult = "this is a <u>handbag</u>." + "<li>this <b>is</b> a html<font size='18' color='#3399ff'> code</font>.90%\n这是测试页 \n\n" + "<a href='event:com' target='_blank'>Flex After Dark.60% \n又是</a></li>";
            td.TdbTitle = "术语，匹配相关10个厂家";
            td.TdbResult = "<img src='http://localhost/catweb/assets/images/5.png'>" + "this's ：这是\n" + "解释：这是什么？\n" + "相关厂家:<a href='event:www.baidu.com' target='_blank'>百度<\a>";
            //GetIndexServer( userid );
            return td;
        }

        private IndexServerData GetPrivateServer( int userid)
        {
            return GetPrivateServer(userid, "index1");
        }
        private IndexServerData GetPrivateServer( int userid, string index)
        {
            GetIndexServer(userid,"/cluster/indexserver/index");
            if (m_IndexTable.ContainsKey(index))
            {
                return m_IndexTable[index] as IndexServerData;
            }
            return null;
        }
        private IndexServerData GetMainIndexServer(int userid)
        {
            return GetMainIndexServer(userid, "mainindex1");
        }
        private IndexServerData GetMainIndexServer( int userid, string index)
        {
            GetIndexServer(userid, "/cluster/indexserver/mainindex");
            if (m_IndexTable.ContainsKey(index))
            {
                return m_IndexTable[index] as IndexServerData;
            }
            return null;
        }
        private void GetIndexServer(int userid, string sPath)
        {
            string sxml = BaseData.GetSysBaseData(17);
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.LoadXml( sxml );
                XmlElement xe = doc.DocumentElement;
                XmlNodeList xnl = doc.SelectNodes( sPath );
                foreach( XmlNode xn in xnl){
                    IndexServerData isd = new IndexServerData();
                    isd.userid = userid.ToString();

                    isd.id = xn.Attributes["id"].Value;
                    isd.ip = xn.Attributes["ip"].Value;
                    isd.enginx = Convert.ToInt32(xn.Attributes["enginx"].Value);
                    foreach ( XmlNode cxn in xn.ChildNodes)
                    {
                        isd.from = Convert.ToInt32(cxn.Attributes["from"].Value);
                        isd.to = Convert.ToInt32(cxn.Attributes["to"].Value);
                        isd.root = cxn.Attributes["root"].Value;
                        isd.Capability = cxn.Attributes["max"].Value;
                        if (userid >= isd.from && userid <= isd.to)
                        {
                            isd.subdir = GetIndexPath( isd.userid );//合理区间 得到 相对索引 路径
                            //isd.path = isd.root + isd.subdir  +isd.userid;
                            XmlNode dbnode = cxn.FirstChild;
                            isd.dbserver = new DbServerData();
                            isd.dbserver.type = dbnode.Attributes["type"].Value;
                            isd.dbserver.ip = dbnode.Attributes["ip"].Value;
                            isd.dbserver.usr = dbnode.Attributes["usr"].Value;
                            isd.dbserver.ps = dbnode.Attributes["ps"].Value;
                            isd.dbserver.port = dbnode.Attributes["port"].Value;
                            isd.dbserver.average = dbnode.Attributes["average"].Value;
                            isd.dbserver.itable = GetTableIndex(isd.userid);

                            dbnode = dbnode.FirstChild;  //tms
                            isd.dbserver.tmsname = dbnode.Attributes["name"].Value;
                            isd.dbserver.tmstable = isd.dbserver.tmsname.Replace("|T|", isd.dbserver.itable);
                            isd.dbserver.tmsquery = dbnode.Attributes["sql"].Value;

                            dbnode = dbnode.NextSibling; //tdb
                            isd.dbserver.tdbname = dbnode.Attributes["name"].Value;
                            isd.dbserver.tdbtable = isd.dbserver.tdbname.Replace("|T|", isd.dbserver.itable);
                            isd.dbserver.tdbquery = dbnode.Attributes["sql"].Value;
                            
                        }
                    }
                    if (!m_IndexTable.ContainsKey(isd.id))
                    {
                        m_IndexTable.Add(isd.id, isd);
                    }
                } 
            }
            catch (System.Exception )
            { }
        }

        private string GetIndexPath( string sid)
        {
            int id = Convert.ToInt32(sid) - 1;
            int div = 500 ;
            int from = id / div *div  +1;
            int to = id / div *div + div;
            string tmp = from.ToString() + "~" + to.ToString() ;
            return tmp + "/";
        }
        private string GetTableIndex( string sid)
        {
            int id = Convert.ToInt32(sid) - 1 ;
            int div = 1000;
            int index = id / div + 1;
            return index.ToString();
        }

        public NPClass FindSentence( NPClass npclass)
        {
            if (npclass == null)
            {
                npclass = new NPClass();
            }else{
                if (npclass.IndSPrivate.ip == null || npclass.DbSPrivate.ip ==null)
                {
                    npclass.IndSPrivate = GetPrivateServer(npclass.UserID );
                    npclass.IndSMain = GetMainIndexServer(npclass.UserID);
                }

                ICatFactory factory = null; 
                ICATEngine engine = null;
                if (npclass.CatFactoryID > 0) 
                {
                    switch (npclass.CatFactoryID)
                    {
                        case 1: factory = new MainTMSFactory(); break;
                        case 2: factory = new MainTDBFactory(); break;
                        case 3: factory = new PrivateTMSFactory(); break;
                        case 4: factory = new PrivateTDBFactory(); break;
                    }
                    engine = factory.CreateEngine();
                    engine.m_npc = npclass;
                    engine.CommandExe();
                }else{
                    if ( npclass.CommandCode == 2)// save
                    {
                        npclass.CatFactoryID = 3;
                        FindSentence(npclass);
                    }else if(npclass.CommandCode == 3) {//fuzzy
                        npclass.CatFactoryID = 3;
                        FindSentence(npclass);
                        CatMakeData CatMd = new CatMakeData();
                        CatMd.m_npclass = npclass;
                        CatMd.TdPrivate = npclass.transdata;
                        if (npclass.transdata.TmsSearchLevel > CLangSegment.SUMKEYINDEXTYPE || npclass.transdata.TmsSearchLevel == 0)
                        {
                            npclass.CatFactoryID = 1;
                            FindSentence(npclass);
                            CatMd.TDMain = npclass.transdata;
                        }
                        CatMd.MaketransTMSData();  //产生TMS数据


                        npclass.CatFactoryID = 4;
                        FindSentence(npclass);
                        CatMd.TdPrivate = npclass.transdata;
                        if ( npclass.transdata.ArrList.Count == 0)
                        {
                            npclass.CatFactoryID = 2;
                            FindSentence(npclass);
                            CatMd.TDMain = npclass.transdata;
                        }
                        CatMd.MaketransTDBData();//产生TDB数据
                    }
                }
                
            }
            return npclass; 
        }

       
        public string Send()
        {
            NPClass np = new NPClass();
            np.UserID = 2;
            np.CommandCode = (int)CatSentenceAnalyzer.CatIndexClass.ENUMCOMMAND.FUZZYINDEX;
            np.IndSPrivate = GetPrivateServer(np.UserID);
            //np.DbS = np.IndS.dbserver;
            
            np.EnginxID = 1; np.FileID = 1;
            np.transdata.OSentence = "engine mine"; np.transdata.TSentence = "你们都是工程师国际歌.";
            np.transdata.textTmsField = "ttxt"; np.transdata.indexTmsField = "otxt"; np.transdata.TmsID = 18;
            np.transdata.OLibrary = "i'm engine  mine?? and you?"; np.transdata.TLibrary = "你是工程"; 
            np.transdata.textTdbField = "tterm"; np.transdata.indexTdbField = "oterm";np.transdata.TdbID = 2;
            //np.transdata.oTerm = "oterm"; np.transdata.tTerm = "tterm";
            //np.transdata.oText = "otxt"; np.transdata.tText = "ttxt";

            ICatFactory factory = null; 
            factory = new MainTDBFactory();
            ICATEngine engine = factory.CreateEngine();
            engine.m_npc = np;
            engine.CommandExe();
            return "";
        }
        
        public NPClass SendCommand(){
            NPClass np = new NPClass();
            np.UserID = 2;
            np.CommandCode = 8;
            np.IndSPrivate = GetPrivateServer(np.UserID);
            //np.DbS = np.IndS.dbserver;

            np.transdata = new TransData();
            np.transdata.TmsID = 21;
            //np.transdata.Osentence = "i'm engine  mine?? and you?"; np.transdata.Tsentence = "你们都是工程师.";
            //np.enginx_type = 1; np.fileid = 1;np.textField = "tterm"; np.indexField = "oterm";np.oTerm = "oterm"; np.tTerm = "tterm";

            //IndexServer indexs = new IndexServer();
            //indexs.m_np = np;
            //indexs.CommandExe();
            return np;
        }

        public NPClass SendCommand(int commandtype, int userid, string osentence, string tsentence)
        {
            DateTime dt = DateTime.Now;
            IInterProcessConnection ipc = null;
            NPClass np = new NPClass();
            np.UserID = userid;
            np.IndSPrivate = GetPrivateServer(np.UserID); 
            //np.DbS = np.IndS.dbserver;
            np.transdata = new TransData();
            if (np.IndSPrivate == null) 
                return null;
            np.CommandCode = commandtype; np.transdata.OSentence = "liu"; np.transdata.TSentence = "刘";
            byte[] data = Utility.Serialize(np);

            try
            {
                ipc = new ClientPipeConnection(NAMEPIPE , np.IndSPrivate.ip);
                ipc.Connect();
                ipc.WriteBytes(data);
                
                data = ipc.ReadBytes();
                np = Utility.Deserialize(data) as NPClass;
                ipc.Close();
            }
            catch (System.Exception e)
            {
                ipc.Dispose();
                np.error = e.Message;
                //np.tm = DateTime.Now.Subtract(dt).Milliseconds.ToString();
            }
            return np;
        }

        
    }
}
